package role

import (
	"sanguo/cluster"
	"sanguo/node/common/transaction"
	"sanguo/node/node_game"
	table_BattleLevel "sanguo/node/table/excel/table/BattleLevel"
	ss_msg "sanguo/protocol/ss/message"
	ss_rpc "sanguo/protocol/ss/rpc"
	"sanguo/rpc/leaveMap"
	"time"

	"github.com/golang/protobuf/proto"
)

//玩家断线 做清理处理
func (this *RoleModule) OffLine() {
	_role := this.CurrentRole()
	if _role != nil && _role.IsRoleModleData() {

		this.ClearTeam()

	}
}

//请求将角色在地图中的对象销毁(不改变角色的所在地图和坐标，角色下次请求进入地图时还会在原地图上创建角色)
func (this *RoleModule) ClearMap() {

	if nil == this.currentRole || this.currentRole.NodeMap == nil {
		return
	}
	this.currentRole.LeaveChat()
	node_game.Infoln(this.user.GetUserID(), this.CurrentRole().GetID(), "ClearMap")
	arg := &ss_rpc.LeaveMapReq{
		MapType: proto.Int32(this.currentRole.GetMapID()),
		UserID:  proto.String(this.user.GetUserID()),
	}
	leaveMap.AsynCall(*this.currentRole.NodeMap, arg, transaction.TransTimeoutMs, func(resp *ss_rpc.LeaveMapResp, err error) {
		if nil == err && resp.GetOk() == 1 {
			this.currentRole.NodeMap = nil
		}
	})
}

//断线后清理副本
func (this *RoleModule) ClearInstanceZone() {

	if nil == this.currentRole {
		return
	}

	role := this.CurrentRole()

	instanceZone := role.GetInstanceZone()
	if instanceZone != nil {
		IZDef := table_BattleLevel.Table_.IDMap[instanceZone.ID]
		if IZDef.IsReconnet {
			role.ClearInstanceZone()
			//			izResp := role.GetInstanceZone().PackAllAward()
			//			izResp.Errcode = cs_message.EnumType(cs_message.EnumType_OK).Enum()
			//			this.user.Reply(0, izResp)
		} else {
			role.ClearInstanceZone()
		}
	}

	if role.GetBattleGround() != nil {
		role.ClearBattleGround()
	}

}

func (this *RoleModule) OnLogout() {
	now := time.Now().Unix()
	if nil != this.currentRole && this.currentRole.IsRoleModleData() {
		this.currentRole.SetLastLogout(now)
	}
}

func (this *RoleModule) ClearTeam() {
	_role := this.CurrentRole()
	req := &ss_msg.OnOroffLine{
		MsgType: proto.Int32(1),
		UserID:  proto.String(_role.GetUserID()),
		RoleID:  proto.Uint64(_role.GetID()),
	}
	cluster.PostMessage(node_game.GetTeamServer().ToPeerID(), req)

}

//玩家重连 验证信息
func (this *RoleModule) OnLine() {
	_role := this.CurrentRole()
	if _role != nil && _role.IsRoleModleData() {

		this.ResetTeam()

	}
}

func (this *RoleModule) ResetTeam() {
	_role := this.CurrentRole()
	req := &ss_msg.OnOroffLine{
		MsgType: proto.Int32(2),
		UserID:  proto.String(_role.GetUserID()),
		RoleID:  proto.Uint64(_role.GetID()),
	}
	cluster.PostMessage(node_game.GetTeamServer().ToPeerID(), req)

}
